package com.example.huazong.myapplication;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.widget.SlidingPaneLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;


import com.example.huazong.myapplication.adapters.RecyclerAdapter;
import com.example.huazong.myapplication.beans.Datas;
import com.example.huazong.myapplication.beans.ItemBean;
import com.example.huazong.myapplication.bottomnavigation.BottomNavigationActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 总结：
 * 1.首先我们要有这个控件，，RecyclerView是在V7包下的
 * 添加这个RecyclerView依赖，才能在布局文件中使用到这个控件
 * 2.通过findViewById找到控件
 * 3.准备好数据
 * 4.设置布局管理器
 * 5.创建适配器
 * 6.设置适配器
 * 7.数据实现
 */
public class ThirdActivity extends AppCompatActivity{


    ListView lv_cd;

    SlidingPaneLayout sp;
    String[] data1 = {"我的钱包", "我的收藏", "设置", "退出"};
    RecyclerView mlist;
    List mData;
    public RecyclerAdapter adapter;
    public SwipeRefreshLayout mrefresh_layout;
    public Intent intent;
    int position;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.third_main);

        //左滑隐藏界面
        sp = (SlidingPaneLayout) findViewById(R.id.sp);
        lv_cd = (ListView) findViewById(R.id.lv_cd);
        ArrayAdapter<String> Madpter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data1);
        lv_cd.setAdapter(Madpter);
        sp.setParallaxDistance(200);
        lv_cd.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                这里写了两种方法if和Switch
//                position 表示adapter 数据源的第几条数据 ，从 0 开始
//                id 表示id,也是从开始
//                此处为提高代码的复用性选择了Switch语句
                switch (position) {
                    case 2:
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mIntent();
                            }
                        }, 2000);
                        break;
                    case 3:
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mAlerDialog();
                                mintent();


                            }
                        }, 2000);
                        break;

                }
                /*if (id == 2) {
                    mIntent();
                }*/
            }

            private void mIntent() {
                intent = new Intent(ThirdActivity.this, HideListViewActivity.class);
                startActivity(intent);
            }

        });

        //找到recyclerView控件
        mlist = (RecyclerView) this.findViewById(R.id.recycler_View);
        mrefresh_layout = (SwipeRefreshLayout) this.findViewById(R.id.refresh_layout);
        //准备数据
        initData();
        //设置默认的显示样式为垂直标准
        showList(true, false);
        //处理下拉刷新
        handlerDownPullUpdate();


        //ItemTouchHelper 用于实现 RecyclerView Item 拖曳效果的类
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {

            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                //actionState : action状态类型，有三类 ACTION_STATE_DRAG （拖曳），ACTION_STATE_SWIPE（滑动），ACTION_STATE_IDLE（静止）
                int dragFlags = makeFlag(ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.UP | ItemTouchHelper.DOWN
                        | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);//支持上下左右的拖曳
                int swipeFlags = makeMovementFlags(ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);//表示支持左右的滑动
                return makeMovementFlags(dragFlags, swipeFlags);//直接返回0表示不支持拖曳和滑动
            }

            /**
             * @param recyclerView attach的RecyclerView
             * @param viewHolder 拖动的Item
             * @param target 放置Item的目标位置
             * @return
             */
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();//要拖曳的位置
                int toPosition = target.getAdapterPosition();//要放置的目标位置
                Collections.swap(mData, fromPosition, toPosition);//做位置的交换
                adapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            /**
             * @param viewHolder 滑动移除的Item
             * @param direction
             */
            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

                position = viewHolder.getAdapterPosition();//获取要滑动删除的Item位置
                mAlerDialog_delete();


            }

        });
        itemTouchHelper.attachToRecyclerView(mlist);
//        OnCreate方法




    }

    public void mAlerDialog_delete() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ThirdActivity.this);
        builder.setTitle("确认");
        builder.setIcon(R.drawable.icon7);
        builder.setMessage("是否确认删除");

        builder.setPositiveButton("确定", new ThirdActivity.okClick());


        builder.show();
    }

    private void mAlerDialog() {
        final AlertDialog.Builder mBuilder = new AlertDialog.Builder(ThirdActivity.this);

        //设置对话框的标题、图标、提示信息内容
        mBuilder.setTitle("确认");
        mBuilder.setIcon(R.drawable.icon7);
        mBuilder.setMessage("是否确认退出");

        //调用对话框对象的setPositiveButton方法为AlertDialog对话框内部设置按钮
        mBuilder.setPositiveButton("确定", new ThirdActivity.okClick());
        mBuilder.create();
        mBuilder.show();


    }

    //跳转界面方法
    private void mintent() {
        intent = new Intent(ThirdActivity.this, MainActivity.class);
        startActivity(intent);
    }
    //跳转聊天界面
    private void IntentChat(){
        intent = new Intent(ThirdActivity.this, MainChat.class);
        startActivity(intent);
    }


    private void handlerDownPullUpdate() {
        mrefresh_layout.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark, R.color.colorAccent);
        mrefresh_layout.setEnabled(true);
        mrefresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //在这里执行刷新数据的操作
                /**
                 * 当我们在顶部下拉的时候，这个方法就会被触发
                 * 但是这个方法石主线程，不可以执行耗时操作
                 * 一般来说我们去请求数据再开一个线程去获取
                 * 这里演示的话，直接添加一条数据
                 */
//                添加数据
                ItemBean data = new ItemBean();
                data.title = "我是新添加的联系人...";
                data.icon = R.mipmap.dp5;
                mData.add(0, data);
                //更新UI
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //更新列表
                        adapter.notifyDataSetChanged();
                        //让刷新停止
                        mrefresh_layout.setRefreshing(false);
                    }
                }, 3000);//3000毫秒=3秒

            }
        });
    }

    private void initListener() {
        //recyclerView没有ListView中已经封装好的OnItemSelected点击事件
        //方法中定义接口 实现RecyclerView的点击方法
        adapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(int position) {
                //这里处理条目的点击事件
                IntentChat();

            }
        });

    }

    //创建初始化模拟数据
    private void initData() {
        //List<DataBea>---->Adapter----->setAdapter----->显示数据

        //创建一个集合
        mData = new ArrayList<>();
        //创建模拟数据
        for (int i = 0; i < Datas.icons.length; i++) {
            //创建数据对象
            ItemBean data = new ItemBean();
            data.icon = Datas.icons[i];
            data.title = "我是第" + i + "个联系人";
            //添加到集合里面
            mData.add(data);
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(1, 3, 3, "多媒体");
        menu.add(1, 2, 2, "拍一拍");
        menu.add(1, 6, 6, "垂直反向");
        menu.add(1, 7, 7, "垂直标准");
        menu.add(1, 8, 8, "水平标准");
        menu.add(1, 9, 9, "水平反向");

        return super.onCreateOptionsMenu(menu);

    }

    //VERTICAL 垂直
    //HORIZONTAL 水平
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //垂直反向
            case 6:
                showList(true, true);
                break;
            //垂直标准
            case 7:
                showList(true, false);
                break;
            //水平标准
            case 8:
                showList(false, false);
                break;
            //水平反向
            case 9:
                showList(false, true);
                break;
            case 2:
                OpenCamera();
                break;
            case 3:
                mIntent();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    //跳转多媒体
    private void mIntent() {
        Intent myIntent = new Intent(ThirdActivity.this,BottomNavigationActivity.class);
        startActivity(myIntent);
    }




    /*
    这个方法用于显示ListView一样的效果
     */
    private void showList(boolean isVertical, boolean isReverse) {
        //RecyclerView需要设置样式，其实就是设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器来控制
        layoutManager.setOrientation(isVertical ? LinearLayoutManager.VERTICAL : LinearLayoutManager.HORIZONTAL);
        //设置水平还是垂直
        //设置标准（正向）还是反向
        layoutManager.setReverseLayout(isReverse);

        mlist.setLayoutManager(layoutManager);
        //创建适配器
        adapter = new RecyclerAdapter(mData);
        //设置到RecyclerView中
        mlist.setAdapter(adapter);
        //初始化事件
        initListener();

    }

    public void OpenCamera() {
        //打开照相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        String path = "storage/sdcard/picture1.jpg";
        File pic = new File(path);
        Uri uri = Uri.fromFile(pic);
        //设定拍照后照片保存位置
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivity(intent);
    }


    //创建OnClickListener接口的内部类并重写OnClick方法
    class okClick implements DialogInterface.OnClickListener {
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.cancel();//关闭对话框
            mData.remove(position);//删除数据
            adapter.notifyItemRemoved(position);


        }

    }

}
